/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ssau.managed;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import ru.ssau.datamanager.DataManager;
import ru.ssau.entities.DataAccessException;
import ru.ssau.entities.Message;


@Named("message")
@SessionScoped
public class MessageBean implements Serializable {

    public static final String ADD = "Add message";
    public static final String EDIT = "Edit message";
    public static final String NO_MESSAGE_TO_EDIT = "noMessageToEdit";
    public static final String VIEW = "View";
    public static final String SEARCH = "Search messages";

    @EJB
    private DataManager dataManager;

    private String searchParameter;
    private Integer selectedMessageId;
    private Message currentMessage;
    private Integer newUserId;
    private Integer newThreadId;
    private Boolean setCurrentDate;
    private String action;

    List<Message> searchResult;

    public MessageBean() {

    }

    public String getCaption() {
        if(currentMessage == null) return null;
        return currentMessage.getCaption();
    }

    public void setCaption(String caption) {
        currentMessage.setCaption(caption);
    }

    public Date getPostDate() {
        if(currentMessage == null) return null;
        return currentMessage.getPostDate();
    }

    public void setPostDate(Date date) {
        if(setCurrentDate) {
            date = new Date();
        }
        currentMessage.setPostDate(date);
    }

    public String getText() {
        if(currentMessage == null) return null;
        return currentMessage.getText();
    }

    public void setText(String text) {
        currentMessage.setText(text);
    }

    public Integer getUserId() {
        if(currentMessage == null) return null;
        return currentMessage.getUserId();
    }

    public void setUserId(Integer userId) {
        newUserId = userId;
    }

    public Integer getThreadId() {
        if(currentMessage == null) return null;
        return currentMessage.getThreadId();
    }

    public void setThreadId(Integer threadId) {
        newThreadId = threadId;
    }


    //Получение параметра поиска (в окне поиска
    //каждый раз устанавливается пустое значение)
    public String getSearchParameter() {
        return "";
    }

    public void setSearchParameter(String searchParameter) {
        this.searchParameter = searchParameter;
    }

    //Формирование списка пользователей для отображения
    public Map<String, Integer> getAllMessages() throws DataAccessException {
        Collection<Message> messages = dataManager.getAllMessages();
        Map<String, Integer> messageMap = new LinkedHashMap<String, Integer>();

        for(Message message: messages) {
            String description = String.format("%d. %s", message.getId(), message.getCaption());
            messageMap.put(description, message.getId());
        }
        if(messageMap.size() < 1) {
            currentMessage = null;
        }

        return messageMap;
    }

    //id текущего пользователя (того, который выбран для отображения)
    public Integer getSelectedMessageId() {
        return selectedMessageId;
    }

    public void setSelectedMessageId(Integer selectedMessageId) {
        this.selectedMessageId = selectedMessageId;
    }

    //Флаг, говорящий о том, что в качестве даты регистрации
    //пользователя устанавливается текущая дата
    public Boolean getSetCurrentDate() {
        return setCurrentDate;
    }

    public void setSetCurrentDate(Boolean setCurrentDate) {
        this.setCurrentDate = setCurrentDate;
    }

    public void search() throws DataAccessException {
        Collection<Message> foundMessages = dataManager.findMessagesByCaption(searchParameter);
        searchResult = new LinkedList<Message>(foundMessages);
        action = SEARCH;
    }

    public List<Message> getSearchResult() {
        return searchResult;
    }

    public String getAction() {
        return action;
    }

    public void doAction() throws DataAccessException {
        if(action.equals(ADD)) {
            add();
        } else {
            edit();
        }
        selectedMessageId=null;
        action = VIEW;
    }

    public void add() throws DataAccessException {
        dataManager.addMessage(currentMessage, newUserId, newThreadId);
    }

    public void edit() throws DataAccessException {
        dataManager.replaceMessage(currentMessage, newUserId, newThreadId);
    }

    //Удаление сущности
    public void delete() throws DataAccessException {
        dataManager.deleteMessageById(selectedMessageId);
        action = VIEW;
        currentMessage = null;
    }

    //Удаление сущности из списка найденных
    public void deleteFromSearchResult(Message message) throws DataAccessException {
        dataManager.deleteMessageById(message.getId());
        searchResult.remove(message);
        action = null;
    }

    public void editFromSearchResult(Message message) {
        currentMessage = message;
        action = EDIT;
    }

    public void setCurrentMessage() throws DataAccessException {
        currentMessage = dataManager.getMessageById(selectedMessageId);
    }

    public void ensureCurrentMessageSet() throws DataAccessException {
        if(currentMessage == null) {
            action = NO_MESSAGE_TO_EDIT;
        } else {
            //work around-ец. Снова.
            if(currentMessage.getId() == null) {
                currentMessage = dataManager.getMessageById(selectedMessageId);
                if(currentMessage == null) {
                    action = NO_MESSAGE_TO_EDIT;
                } else {
                    setCurrentDate = false;
                   // newUserId = currentMessage.getUserId();
                  //  newThreadId = currentMessage.getThreadId();
                    action = EDIT;
                }
            } else {
                setCurrentDate = false;
              //  newUserId = currentMessage.getUserId();
              //  newThreadId = currentMessage.getThreadId();
                action = EDIT;
            }
        }
    }

    public void unsetCurrentMessage() {
        currentMessage = new Message();
        setCurrentDate = true;
        action = ADD;
    }
}